package com.hhd.listener;

import com.alibaba.fastjson.JSONObject;
import com.hhd.pdf.GeneratorParameters;
import com.hhd.pdf.PdfGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class TestListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    @Lazy
    PdfGenerator generator;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        test1();
    }

    private void test1() {
        GeneratorParameters parameters = GeneratorParameters.builder()
                .configPath("/config.xml")
                .outputPath("E:\\temp\\2024年1月26日\\1.pdf")
                .renderData(readData("JSONData"))
                .build().init();
        generator.generate(parameters);
    }

    private JSONObject readData(String fileName) {
        try (InputStream inputStream = this.getClass().getResourceAsStream("/" + fileName + ".json")) {
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes);
            return JSONObject.parseObject(new String(bytes, StandardCharsets.UTF_8));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
